package com.ocom.payconfig.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;

import java.net.URLEncoder;
import java.util.*;
import java.util.logging.Logger;

public class WeiMiUtil {
    public static final String appId = "dd23c28568e29d1acae65cb575158dc3";
    public static final String secretKey = "?F>O%9+>\"HC}D_Gq>(5E";
    public static final String URL = "https://vm.weimi24.com/v8/third-center-web"; //正式环境

    private static final Logger logger = Logger.getLogger(WeiMiUtil.class.getName());
    //获取设备信息 http://docs.weimi24.com:61900/web/#/33/1570
    public static String device(Map<String,Object> param){
        String url = URL + "/ext/device-profile";
//        param.put("payChannelCodeInt","11001");
//        param.put("authType",7);
//        param.put("payEndTime",System.currentTimeMillis());
        return get(url,param);
    }

    //下单接口 http://docs.weimi24.com:61900/web/#/33/1563
    public static String shipment(Map<String,Object> param){
        String url = URL+"/ext/notify-shipment";
        return post(url, param);
    }

    //订单查询:http://docs.weimi24.com:61900/web/#/33/1564
    public static String queryOrderList(Map<String,Object> params){
        String url = URL + "/ext/query-order-list";
        return get(url,params);
    }

    //http://docs.weimi24.com:61900/web/#/33/1513
    public static String deviceInfo(Map<String,Object> params){
        String url = URL + "/ext/device-info";
        return get(url,params);
    }


    public static Map<String, String> getHeadMap(String orgId, String secretKey, Map<String, Object> param) {
        String nonce = UUID.randomUUID().toString().replaceAll("-", "");
        Long timestamp = System.currentTimeMillis();
        ApiSignGenerator apiSignGenerator = ApiSignGenerator.builder().nonce(nonce).timestamp(timestamp).appId(orgId).secretKey(secretKey).build();
        String signValue = apiSignGenerator.generate(param);
        Map<String, String> header = new HashMap<>();
        header.put("Client-Type", "EXTERNAL");
        header.put("SIGN", signValue);
        header.put("TIMESTAMP", timestamp + "");
        header.put("NONCE", nonce);
        header.put("APP_ID", orgId);
        return header;
    }

    public static String post(String url, Map<String, Object> param) {
        Map<String, String> headMap = getHeadMap(appId, secretKey, param);
        HttpRequest getRequest = HttpUtil.createPost(url);
        getRequest.body(JSONUtil.toJsonStr(param));
        headMap.forEach(getRequest::header);
        String result = getRequest.execute().body();
        logger.info(String.format("微米请求：URL【%s】，参数：【%s】,请求头：【%s】,返回结果：【%s】", url, JSON.toJSONString(param),JSON.toJSONString(headMap),result));
        return result;
    }

    public static String get(String url, Map<String, Object> param){
        StringBuilder urlBuilder = new StringBuilder(url);
        boolean firstParam = true;
        try {
            for (Map.Entry<String,Object> entry : param.entrySet()) {
                if (firstParam) {
                    urlBuilder.append("?");
                    firstParam = false;
                } else {
                    urlBuilder.append("&");
                }
                String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
                String encodedValue = URLEncoder.encode(entry.getValue().toString(), "UTF-8");

                urlBuilder.append(encodedKey).append("=").append(encodedValue);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        url = urlBuilder.toString();
        Map<String, String> headMap = getHeadMap(appId, secretKey, param);
        String result = HttpRequest.get(url).addHeaders(headMap).execute().body();
        logger.info(String.format("微米请求：URL【%s】，参数：【%s】,请求头：【%s】,返回结果：【%s】", url, JSON.toJSONString(param),JSON.toJSONString(headMap),result));
        return result;
    }
}
